package com.elinkway.infinitemovies.ui.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Animatable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.elinkway.infinitemovies.adaction.CommonAdActionHandle;
import com.elinkway.infinitemovies.adapter.MainFragmentStatePagerAdapter;
import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.async.RequestMainHeaderTask;
import com.elinkway.infinitemovies.async.RequestResultListener;
import com.elinkway.infinitemovies.bean.LocalVideoEpisode;
import com.elinkway.infinitemovies.bean.MainHeaderBean;
import com.elinkway.infinitemovies.bean.MainHeaderList;
import com.elinkway.infinitemovies.bean.NewAdDataBean;
import com.elinkway.infinitemovies.bean.PlayData;
import com.elinkway.infinitemovies.bean.PlayRecord;
import com.elinkway.infinitemovies.bean.ServerPayload;
import com.elinkway.infinitemovies.bigdata.BigDataApi;
import com.elinkway.infinitemovies.bigdata.BigDataConstants;
import com.elinkway.infinitemovies.config.SettingManage;
import com.elinkway.infinitemovies.dao.PlayRecordDao;
import com.elinkway.infinitemovies.download.Constants;
import com.elinkway.infinitemovies.http.api.MoviesHttpApi;
import com.elinkway.infinitemovies.http.parser.MainHeaderListParser;
import com.elinkway.infinitemovies.http.requesttask.RequestAdTask;
import com.elinkway.infinitemovies.http.requesttask.RequestAlbumInfoTask;
import com.elinkway.infinitemovies.selfdata.AdRequestStatis;
import com.elinkway.infinitemovies.selfdata.MyDataRecordCreater;
import com.elinkway.infinitemovies.selfdata.SelfDataConstant;
import com.elinkway.infinitemovies.selfdata.bean.LaunchDurationDataRecord;
import com.elinkway.infinitemovies.selfdata.bean.MyDataRecord;
import com.elinkway.infinitemovies.selfdata.dao.RealmDaoManager;
import com.elinkway.infinitemovies.ui.activity.DownloadActivity;
import com.elinkway.infinitemovies.ui.activity.ExtraTabActivity;
import com.elinkway.infinitemovies.ui.activity.LoginActivity;
import com.elinkway.infinitemovies.ui.activity.NewMainActivity;
import com.elinkway.infinitemovies.ui.activity.PlayHistoryActivity;
import com.elinkway.infinitemovies.ui.activity.SearchActivity;
import com.elinkway.infinitemovies.ui.activity.SplashActivity;
import com.elinkway.infinitemovies.ui.activity.VideoDetailActivity;
import com.elinkway.infinitemovies.ui.activity.play.PlayActivitySelfOwn;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.MoviesUtils;
import com.elinkway.infinitemovies.utils.NetWorkTypeUtils;
import com.elinkway.infinitemovies.utils.SharePreferenceManager;
import com.elinkway.infinitemovies.utils.StringUtil;
import com.elinkway.infinitemovies.utils.UIs;
import com.elinkway.infinitemovies.utils.UmengEventPoster;
import com.elinkway.infinitemovies.utils.Utils;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.image.ImageInfo;
import com.flyco.tablayout.SlidingTabLayout;
import com.le123.ysdq.R;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONArray;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class NewHomeFragment extends BaseFragment{

    public static String TAG = "NewHomeFragment";
    /**
     * 控制动画的停止，只要是
     * 动画被点击 或者
     * 跳出了首页 不管次数，回来不在展示动画
     */
    public final String NO_SHAKE_ANIMATION = "shakeAnimation";
    /**
     * 第二天展示动画的逻辑 标识第二天的缓存key
     */
    public final String NEXT_DAY_SHAKE_ANIMATION = "nextDayShake";

    private final String PREFIX = "file://";

    private static final String KEY_SEARCH = "searchKey";

    private SlidingTabLayout mTabs;

    private ViewPager mViewPager;

    private RelativeLayout mAllTabExtranceRl;

    private ImageView mImgAllTabExtrance;

    public static final int ENTRA_ALL_TAB = 1125;

    public static final int RESULT_ALL_TAB = 1126;

    private MainFragmentStatePagerAdapter mainFragmentAdapter;

    private RequestMainHeaderTask mMainHeaderTask;

    private volatile ArrayList<MainHeaderBean> mHeaderList = new ArrayList<>();
    private MainHeaderList mMainHeaderList;

    private LinearLayout rightSearchLl;
    private RelativeLayout searchKeyRl;
    private TextView searchKeywordTv;
    public RelativeLayout mHistoryContinue;
    public RelativeLayout mHistoryClose;
    public RelativeLayout mHistoryPlay;
    public TextView mHistoryTitle;
    private List<PlayRecord> playRecordList;
    private SharedPreferences mLoginSp;
    private Handler mHandler;
    private ImageView tabIv;
    private Bundle mBundle;
    private LaunchDurationDataRecord launchDurationDataRecord;
    private View mLoadingFailed; // 加载失败布局
    private Button mBtnRefresh; // 刷新按钮
    private String strYiDian = ""; // 一点咨询tag

    /**
     * 针对快看显示广告位
     */
    private FrameLayout adContainer;
    private SimpleDraweeView adIcon;
    private ImageView adTip;
    private boolean isVisible = false;

    public static NewHomeFragment newInstance(int position) {
        NewHomeFragment fragment = new NewHomeFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mHandler = new Handler();
        View view = inflater.inflate(R.layout.fragment_newhome, container, false);
        //strYiDian = SharePreferenceManager.getVaule(getContext(), SharePreferenceManager.YIDIAN_TAG, "");
        mBundle = getArguments();
        initViewPager(view);
        initShakeView(view);
        mLoginSp = getActivity().getSharedPreferences(SettingManage.LOGIN_INFO, Context.MODE_PRIVATE);
        if (!TextUtils.isEmpty(mLoginSp.getString(LoginActivity.TOKEN, ""))) {
            playRecordList = new PlayRecordDao(getActivity()).selectFromServer(1);
        } else {
            List<String> noPosterRecordList = new PlayRecordDao(getActivity()).getNoPosterAidList();
            if(noPosterRecordList != null && noPosterRecordList.size() > 0){
                new RequestAlbumInfoTask(getActivity(), noPosterRecordList, "record").start();
            }
            playRecordList = new PlayRecordDao(getActivity()).getLocalAll();
        }
        String oldTabJson = SharePreferenceManager.getVaule(MoviesApplication.getInstance(), SharePreferenceManager.HOME_TAB_JSON, "");
        if (TextUtils.isEmpty(oldTabJson) && !NetWorkTypeUtils.isNetAvailable()) {
            // 无网络无缓存
            mLoadingFailed.setVisibility(View.VISIBLE);
        } else {
            mLoadingFailed.setVisibility(View.GONE);
            setDefaultTabData(oldTabJson);
            initRequest();

        }
        return view;
    }
    // 初始化时的请求
    private void initRequest() {
        requestHeaderList();
        if(getActivity() instanceof NewMainActivity){
            requestShakeAd();
        }
    }

    private void requestHeaderList() {
        mMainHeaderTask = new RequestMainHeaderTask(MoviesApplication.getInstance());
        mMainHeaderTask.setListener(new MainHeaderRequestListner());
        mMainHeaderTask.start();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        super.setFragmentClassName(TAG);
        Log.i(TAG, "onAttach");
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            isVisible = true;
        }

    }

    public void initViewPager(View view) {
        mHistoryContinue = (RelativeLayout) view.findViewById(R.id.rl_continue_history);
        mHistoryPlay = (RelativeLayout) view.findViewById(R.id.rl_history_continue_play);
        mHistoryTitle = (TextView) view.findViewById(R.id.tv_history_continue);
        mHistoryClose = (RelativeLayout) view.findViewById(R.id.rl_history_close);
        mHistoryClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mHistoryContinue.setVisibility(View.GONE);
            }
        });
        searchKeyRl = (RelativeLayout) view.findViewById(R.id.search_keyword_rl);
        rightSearchLl = (LinearLayout) view.findViewById(R.id.right_ll);
        searchKeywordTv = (TextView) view.findViewById(R.id.search_keyword_tv);
        searchKeyRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent searchIntent = new Intent(getActivity(),SearchActivity.class);
//                searchIntent.putExtra("searchKey", mHeaderBean.getSearchQuery());
                searchIntent.putExtra(KEY_SEARCH, searchKeywordTv.getText().toString());
                getActivity().startActivity(searchIntent);
            }
        });
        setRightIconOfSearch();
        mTabs = (SlidingTabLayout) view.findViewById(R.id.main_tabs);
        mViewPager = (ViewPager) view.findViewById(R.id.main_pager);
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                LogUtils.e(TAG, "onPageSelected " + position);
                if (searchKeywordTv != null && mHeaderList != null) {
                    if(position < mHeaderList.size()){
                        try {
                            if (mHeaderList.get(position) != null) {
                                if (!TextUtils.isEmpty(mHeaderList.get(position).getSearchQuery())) {
                                    searchKeywordTv.setText(mHeaderList.get(position).getSearchQuery());
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mAllTabExtranceRl = (RelativeLayout) view.findViewById(R.id.all_tab_entrance_rl);
        mImgAllTabExtrance = (ImageView) view.findViewById(R.id.all_tab_entrance_iv);
        if (MoviesUtils.isProductYsdq() && Constants.TAG_YIDIAN.equals(strYiDian)) {
            mImgAllTabExtrance.setImageResource(R.drawable.img_channel);
        } else {
            mImgAllTabExtrance.setImageResource(R.drawable.all_tab_entrance_icon);
        }
        tabIv= (ImageView) view.findViewById(R.id.tab_iv);
        if (MoviesUtils.isProductCjsp()){
            tabIv.setVisibility(View.GONE);
            mAllTabExtranceRl.setVisibility(View.GONE);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, UIs.dipToPx(50));
            params.rightMargin = 0;
            mTabs.setLayoutParams(params);
        }else {
            tabIv.setVisibility(View.VISIBLE);
            mAllTabExtranceRl.setVisibility(View.VISIBLE);
        }
        mAllTabExtranceRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (MoviesUtils.isProductYsdq() && Constants.TAG_YIDIAN.equals(strYiDian)) {
                    Intent allTabIntent = new Intent(getActivity(), ExtraTabActivity.class);
                    allTabIntent.putExtra(ExtraTabActivity.TAG_YIDIAN, true);
                    startActivityForResult(allTabIntent, ENTRA_ALL_TAB);
                    getActivity().overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                } else {
                    if(mHeaderList != null && mHeaderList.size() > 0){
                        Intent allTabIntent = new Intent(getActivity(), ExtraTabActivity.class);
                        allTabIntent.putExtra("allTabList", mHeaderList);
                        startActivityForResult(allTabIntent, ENTRA_ALL_TAB);
                        getActivity().overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                        MyDataRecord record = MyDataRecordCreater.build(MyDataRecord.class);
                        record.setCur_url("category_navigato");
                        record.setAcode("41");
                        RealmDaoManager.addMyDataRecord(record);
                    }
                }

            }
        });
        mHistoryPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (playRecordList != null && playRecordList.size() > 0) {
                    PlayRecord currplayRecord;
                    currplayRecord = playRecordList.get(0);
                    if (null != currplayRecord) {
                        Map<String, String> dataMap = BigDataApi.createDataMap("0", "","0","-",currplayRecord.getAid(),"-");
                        dataMap.put("rank", 0 + "");
                        dataMap.put("cur_url", BigDataConstants.PGV_CURRENT_ID_HISTORY);
                        BigDataApi.bigDataCommonReport(dataMap, getActivity());

                        String url = currplayRecord.getUrl();
                        if (isLocalUrl(url)) {
                            String fileUrl = url.replace(PREFIX, "").trim();
                            File localFile = new File(fileUrl);
                            //判断当前的URL是否是本地的URL
                            if (null != localFile && localFile.exists()) {
                                PlayData playData = setLocalData(url, currplayRecord);
                                jumpToPlayActivity(playData);
                            } else {

                            }
                        } else {
                            VideoDetailActivity.launch(getActivity(), currplayRecord.getAid(),
                                    currplayRecord.getVt(), currplayRecord.getName(), "", "", "", currplayRecord.getPorder(),"","");
                        }
                    }
                }
            }
        });
        mLoadingFailed = view.findViewById(R.id.video_loading_failed);
        mBtnRefresh = (Button) mLoadingFailed.findViewById(R.id.bn_refresh);
        mBtnRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initRequest();
            }
        });
    }

    private void initShakeView(View view) {
        adContainer = (FrameLayout) view.findViewById(R.id.adContainer);
        adContainer.setVisibility(View.VISIBLE);
        adIcon = (SimpleDraweeView) view.findViewById(R.id.adIcon);
        adTip = (ImageView) view.findViewById(R.id.redTip);
    }

    /**
     * 控制动画开始、停止的切换
     */
    private static boolean isStart = false;
    /**
     * 动画计时器
     */
    private Timer shakeAnimationTimer = null;
    /**
     * 控制动画开始的次数
     */
    private int shakeTime = 0;

    private void showShakeAd(NewAdDataBean result) {
        if (null == result) {
            return;
        }

        final ServerPayload serverPayload = (ServerPayload) result.payload;
        if (null == serverPayload) {
            return;
        }
        String tipIcon = "";
        if (null != result.ext) {
            tipIcon = result.ext.badge;
        }
        if (MoviesUtils.isProductKuaiKan() || MoviesUtils.isProductYsdq()) {
            if (!StringUtil.isEmpty(serverPayload.pic)) {
                //重定向，需要清除缓存
                Fresco.getImagePipeline().clearCaches();
                ControllerListener controllerListener = new BaseControllerListener<ImageInfo>() {
                    @Override
                    public void onFinalImageSet(
                            String id,
                            @Nullable ImageInfo imageInfo,
                            @Nullable Animatable anim) {
                        if (anim != null) {
                            // 其他控制逻辑
                            anim.start();
                        }
                    }
                };

                DraweeController controller = Fresco.newDraweeControllerBuilder()
                        .setUri(Uri.parse(serverPayload.pic))
                        .setControllerListener(controllerListener)
                        .build();
                adIcon.setController(controller);
            }

            if (!StringUtil.isEmpty(tipIcon)) {
                ImageLoader.getInstance().displayImage(tipIcon, adTip);
            }
            umengServerShow();
            adContainer.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    umengServerClick();
                    stopShakeAnimation();
                    CommonAdActionHandle.getInstance().doServerAd(getActivity(), serverPayload, SelfDataConstant.AD_PO_HOMECIRCLE);
                }
            });

            boolean isNextDay = false;
            if (SharePreferenceManager.getVaule(getActivity(), NEXT_DAY_SHAKE_ANIMATION, "0").equals("0") ||
                    isNextDayForShowShake(SharePreferenceManager.getVaule(getActivity(), NEXT_DAY_SHAKE_ANIMATION, "0"), result.ts)) {
                isNextDay = true;
            }

            SharePreferenceManager.saveVaule(getActivity(), NEXT_DAY_SHAKE_ANIMATION, result.ts);
            if (isNextDay) {
                SharePreferenceManager.saveVaule(getActivity(), NO_SHAKE_ANIMATION, false);
                shakeTime = 0;
            }

            if (!StringUtil.isEmpty(serverPayload.pic) && serverPayload.pic.endsWith(".gif")) {
                return; //gif的情况下不展示摇晃动画
            }

            final AnimationSet animationSet = new AnimationSet(true);
            Animation shakeStart = AnimationUtils.loadAnimation(
                    getActivity(), R.anim.shake_start);
            Animation shake = AnimationUtils.loadAnimation(
                    getActivity(), R.anim.shake_animation);
            shake.setStartOffset(200);
            Animation shakeAgain = AnimationUtils.loadAnimation(
                    getActivity(), R.anim.shake_again);
            shakeAgain.setStartOffset(600);
            Animation shakeLast = AnimationUtils.loadAnimation(
                    getActivity(), R.anim.shake_animation);
            shakeLast.setStartOffset(1000);
            Animation shakeEnd = AnimationUtils.loadAnimation(
                    getActivity(), R.anim.shake_end);
            shakeEnd.setStartOffset(1200);
            animationSet.
                    addAnimation(shakeStart);
            animationSet.addAnimation(shake);
            animationSet.addAnimation(shakeAgain);
            animationSet.addAnimation(shakeLast);
            animationSet.addAnimation(shakeEnd);

            final boolean noShake = SharePreferenceManager.getVaule(getActivity(), NO_SHAKE_ANIMATION);
            LogUtils.d(TAG, "------------" + noShake + "");

            if (!noShake && shakeTime < 3) {
                if (shakeAnimationTimer == null) {
                    shakeAnimationTimer = new Timer();
                }
                shakeAnimationTimer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        if (getActivity() != null) {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (!noShake && shakeTime < 3) { //防止前一个判断条件成立后timer一直执行
                                        if (isStart) {
                                            adContainer.clearAnimation();
                                            isStart = false;
                                        } else {
                                            adContainer.startAnimation(animationSet);
                                            isStart = true;
                                            shakeTime++;
                                        }
                                    } else {
                                        stopShakeAnimation();
                                    }
                                }
                            });
                        }
                    }
                }, 100, 1500);
            }
        }
    }

    private void stopShakeAnimation() {
        if (MoviesUtils.isProductKuaiKan() || MoviesUtils.isProductYsdq()) {
            if (adContainer != null) {
                adContainer.clearAnimation();
            }
            if (shakeAnimationTimer != null) {
                shakeAnimationTimer.cancel();
                shakeAnimationTimer = null;
            }
            SharePreferenceManager.saveVaule(getActivity(), NO_SHAKE_ANIMATION, true);
        }
    }

    /**
     * 判断第二天的逻辑
     * @param lastTime 上次保存的时间戳
     * @param currentTime 当前时间戳
     * @return
     */
    private boolean isNextDayForShowShake(String lastTime, String currentTime) {
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yy/MM/dd");
        String[] lastTimeArr = sDateFormat.format(new Date(Long.valueOf(lastTime))).split("/");
        String[] currentTimeArr = sDateFormat.format(new Date(Long.valueOf(currentTime))).split("/");
        if (Integer.valueOf(lastTimeArr[0]) < Integer.valueOf(currentTimeArr[0])) {
            return true;
        }

        if (Integer.valueOf(lastTimeArr[1]) < Integer.valueOf(currentTimeArr[1])) {
            return true;
        }

        if (Integer.valueOf(lastTimeArr[2]) < Integer.valueOf(currentTimeArr[2])) {
            return true;
        }
        return false;
    }
    private void requestShakeAd() {
        if (MoviesUtils.isProductKuaiKan() || MoviesUtils.isProductYsdq()) {
            new RequestAdTask(MoviesApplication
                    .getInstance(), MoviesHttpApi.HOME_SHAKE, new ShakeAdRequestResultListener()).start();
        }
    }

    private class ShakeAdRequestResultListener implements
            RequestResultListener<NewAdDataBean> {

        @Override
        public boolean onRequestFailed() {
            LogUtils.e(TAG, "!!!!!!!!!!!!!!请求广告数据失败!!!!!!!!!!!!!!");
            return false;
        }

        @Override
        public void onRequestSuccess(int updateId, NewAdDataBean result) {
            LogUtils.e(TAG, "!!!!!!!!!!!!!!AdDataBean：" + result);
            if (result != null) {
                AdRequestStatis.selfResponseReport(result, SelfDataConstant.AD_PO_HOMECIRCLE);
                showShakeAd(result);
                LogUtils.e(TAG, "!!!!请求广告数据成功!!!!");
            }
        }

        @Override
        public void onPreRequest() {

        }
    }

    private void umengServerShow() {
        HashMap<String, String> propertyMap = new HashMap<>();
        propertyMap.put("position", "homecircle");
        UmengEventPoster.doPost(UmengEventPoster.SERVER_SHOW, propertyMap);

        AdRequestStatis.selfReportAdShow(SelfDataConstant.AD_SERVER, "homecircle");
    }

    private void umengServerClick() {
        HashMap<String, String> propertyMap = new HashMap<>();
        propertyMap.put("position", "homecircle");
        UmengEventPoster.doPost(UmengEventPoster.SERVER_CLICK, propertyMap);

        AdRequestStatis.selfReportAdClick(SelfDataConstant.AD_SERVER, "homecircle");
    }

    public void showHistory() {
        if (playRecordList.size() > 0) {
            mHistoryContinue.setVisibility(View.VISIBLE);
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (mHistoryContinue.getVisibility() == View.VISIBLE) {
                        mHistoryContinue.setVisibility(View.GONE);
                    }
                }
            }, 3000);
            if (playRecordList != null && playRecordList.size() > 0) {
                mHistoryTitle.setText(playRecordList.get(0).getName());
            }
        }
    }

    private boolean isLocalUrl(String url) {
        String prefix = "file:///";
        return !TextUtils.isEmpty(url) && url.startsWith(prefix);
    }

    private void jumpToPlayActivity(PlayData playData) {
        Intent intent = new Intent(getActivity(), PlayActivitySelfOwn.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(Utils.PLAY_DATA, playData);
        intent.putExtras(bundle);
        getActivity().startActivity(intent);
    }

    private PlayData setLocalData(String url, PlayRecord currplayRecord) {
        //设置本地视频播放的相关数据
        ArrayList<String> Url = new ArrayList<String>();
        Url.add(url);
        LocalVideoEpisode localVideoEpisode = new LocalVideoEpisode();
        localVideoEpisode.setAid(currplayRecord.getAid());
        localVideoEpisode.setPorder(currplayRecord.getPorder());
        localVideoEpisode.setName(currplayRecord.getName());
        localVideoEpisode.setVt(currplayRecord.getVt());
        localVideoEpisode.setPlay_url(Url);
        ArrayList<LocalVideoEpisode> localVideoEpisodeList = new ArrayList<LocalVideoEpisode>(1);
        localVideoEpisodeList.add(localVideoEpisode);
        PlayData playData = new PlayData();
        //设置播放的是本地的文件
        playData.setIsLocalVideo(true);
        playData.setmLocalDataLists(localVideoEpisodeList);
        playData.setPorder(currplayRecord.getPorder());//知道播的是哪一集播放器
        playData.setAid(currplayRecord.getPorder());
        playData.setmPlayRecord(currplayRecord);

        return playData;
    }

    private void setRightIconOfSearch() {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(UIs.dipToPx(35), UIs.dipToPx(20));
        ImageView historyIv = new ImageView(getActivity());
        historyIv.setLayoutParams(params);
        historyIv.setPadding(UIs.dipToPx(5), 0 , UIs.dipToPx(10), 0);
        historyIv.setImageResource(R.drawable.history_icon_bb_selector);
        historyIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PlayHistoryActivity.launch(getActivity());
            }
        });
        rightSearchLl.addView(historyIv);
        ImageView downloadIv = new ImageView(getActivity());
        downloadIv.setLayoutParams(params);
        downloadIv.setPadding(UIs.dipToPx(10), 0,UIs.dipToPx(5),0);
        downloadIv.setImageResource(R.drawable.download_icon_bb_selector);
        downloadIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(),
                        DownloadActivity.class);
                startActivity(intent);
            }
        });
        rightSearchLl.addView(downloadIv);
        rightSearchLl.setVisibility(View.VISIBLE);
        rightSearchLl.setBackgroundColor(getResources().getColor(R.color.white));
    }

    class MainHeaderRequestListner implements RequestResultListener<MainHeaderList>{

        @Override
        public boolean onRequestFailed() {
            return false;
        }

        @Override
        public void onRequestSuccess(int updateId, MainHeaderList result) {
            if(result != null && result.getHeaderList() != null){
                if (!compareHeaderList(mMainHeaderList,result)) {
                    mMainHeaderList = result;
                    mHeaderList = result.getHeaderList();
                    setShowData(result.getHeaderList());
                }
                if (searchKeywordTv != null && result.getHeaderList().get(0) != null &&
                        !TextUtils.isEmpty(result.getHeaderList().get(0).getSearchQuery())) {
                    searchKeywordTv.setText(result.getHeaderList().get(0).getSearchQuery());
                }
                if (mLoadingFailed.getVisibility() == View.VISIBLE) {
                    mLoadingFailed.setVisibility(View.GONE);
                }
            }
        }

        @Override
        public void onPreRequest() {

        }
    }

    /**
     * 比较本地频道列表与服务器返回数据是否一致
     * @param headerList 本地列表
     * @param result 服务器返回列表
     * @return true 相等，false 不相等
     */
    private boolean compareHeaderList(MainHeaderList headerList, MainHeaderList result) {
        if (headerList != null && headerList.getHeaderList() != null) {
            if (headerList.getHeaderList().size() != result.getHeaderList().size()) {
                return false;
            }
            int size = headerList.getHeaderList().size();
            MainHeaderBean beanHeader = null;
            MainHeaderBean beanResult = null;
            for (int i = 0; i < size; i++) {
                beanHeader = headerList.getHeaderList().get(i);
                beanResult = result.getHeaderList().get(i);
                if (!beanHeader.equals(beanResult)) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }

    private void setDefaultTabData(String oldTabJson) {
        if(mainFragmentAdapter == null){
            if(!TextUtils.isEmpty(oldTabJson)){
                MainHeaderListParser parser = new MainHeaderListParser();
                try {
                    parser.setArr(new JSONArray(oldTabJson));
                    mMainHeaderList = parser.parse(null);
                    if(mMainHeaderList != null){
                        mHeaderList = mMainHeaderList.getHeaderList();
                    }
                    if(mHeaderList == null || mHeaderList.size() < 1){
                        mHeaderList = setOneTabData();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    mHeaderList = setOneTabData();
                }
            }else{
                mHeaderList = setOneTabData();
            }
            setShowData(mHeaderList);
        }
    }

    private ArrayList<MainHeaderBean> setOneTabData(){
        ArrayList<MainHeaderBean> headerList = new ArrayList<>();
        MainHeaderBean bean = new MainHeaderBean();
        bean.setName("推荐");
        // 超级视频
        if (MoviesUtils.isProductCjsp()) {
            bean.setPage("sarrs_index");
        } else {
            bean.setPage("page_index");
        }
        headerList.add(bean);
        return headerList;
    }

    private synchronized void setShowData(List<MainHeaderBean> headerList) {
        if(headerList != null && headerList.size() > 0){
            String[] titleArr = new String[headerList.size()];

            int defaultIndex = 0;
            for (int i=0; i<headerList.size();i++){
                SharePreferenceManager.saveVaule(getContext(),headerList.get(i).getPage(),false);
                titleArr[i] = headerList.get(i).getName();
                if("1".equals(headerList.get(i).getIsDefault())){
                    defaultIndex = i;
                }
            }
            if(mainFragmentAdapter == null){
                if (mBundle != null) {
                    launchDurationDataRecord = (LaunchDurationDataRecord)mBundle.getSerializable(SplashActivity.LAUNCHLOG);
                }
                mainFragmentAdapter = new MainFragmentStatePagerAdapter(getChildFragmentManager(), headerList, getActivity(),headerList.get(defaultIndex).getPage(),launchDurationDataRecord);
                mViewPager.setAdapter(mainFragmentAdapter);
                mViewPager.setOffscreenPageLimit(1);
            }else{
                mainFragmentAdapter.setHeaderList(headerList);
            }
            mTabs.setViewPager(mViewPager,titleArr);
            mTabs.setCurrentTab(defaultIndex);
        }
    }

    public String getCurrentPageIndex(){
        String index = "home_page_index";
        if(mainFragmentAdapter != null){
            HomeTestFragment f = mainFragmentAdapter.getCurrentFragment();
            if(f != null){
                index = f.getmBDPageIndex();
            }
        }
        return index;
    }

    @Override
    public void onResume() {
        Activity currentActivity = getActivity();
        boolean isBackToForeGround = false;
        if (currentActivity instanceof NewMainActivity) {
            isBackToForeGround = ((NewMainActivity) currentActivity).isBackToForeGround;
        }
        if(isVisible && isBackToForeGround) {
            //fragment可见
            requestShakeAd();
            ((NewMainActivity) currentActivity).isBackToForeGround = false;
        }
        super.onResume();

    }

    @Override
    public void onStop() {
        super.onStop();
        if (shakeTime > 0) {
            stopShakeAnimation();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        isVisible = !hidden;
        if(hidden){
        } else {
            Log.i("ggggggggggggg","hhhhhhh");
            if(mainFragmentAdapter != null){
                HomeTestFragment f = mainFragmentAdapter.getCurrentFragment();
                if(f != null){
                    if(getActivity() instanceof NewMainActivity){
                        ((NewMainActivity)getActivity()).setCurrentPageId(f.getmBDPageIndex());
                    }
                    BigDataApi.bigDataPageShowReport(f.getmBDPageIndex(), new HashMap<String, String>(), getActivity());
                    f.resetInscreenData();
                    f.bigdataReportShow();
                }
            }
            if(mHeaderList == null || mHeaderList.size() < 1){
                if (null != mMainHeaderTask && !mMainHeaderTask.isCancelled()) {
                    mMainHeaderTask.cancel();
                    mMainHeaderTask = null;
                }
                mMainHeaderTask = new RequestMainHeaderTask(MoviesApplication.getInstance());
                mMainHeaderTask.setListener(new MainHeaderRequestListner());
                mMainHeaderTask.start();
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == ENTRA_ALL_TAB){
            if(resultCode == RESULT_ALL_TAB){
                if(data != null){
                    MainHeaderBean resultHeader = (MainHeaderBean) data.getSerializableExtra("headerBean");
                    if(resultHeader != null){
                        for (int i=0; i<mHeaderList.size();i++){
                            if(resultHeader.getPage().equals(mHeaderList.get(i).getPage())){
                                mTabs.setCurrentTab(i);
                                break;
                            }
                        }
                    }
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
